#include <tuple>
#include <fstream>
#include <cstring>
#include <string>
#include <vector>
#include <sys/stat.h>
#include <dirent.h>

#include "parser.hpp"
#include "count.hpp"

using namespace std;

int main(int argc, char *argv[]) {

    auto args = parse_args(argc, argv);
    auto file_list = vector<string>(); //Save fileName in a file_list
    DIR* pDir;
    struct dirent* myDirent;
    struct stat s;
    char allName[1024];

    for (int i = 1; i < argc; ++i) {
      string t_arg = string(argv[i]);
      if (t_arg == "-A" || t_arg == "--all" || t_arg == "-b" || t_arg == "-r" || t_arg == "-s" || t_arg == "-h" || t_arg == "--help")
        continue;
      else if (stat(argv[i],&s)==0){
        if(s.st_mode & S_IFDIR){ // Judge whether it's a file or a dir without opening the dir
          if (args.recursive){ // Recursive searching
            GetListR(argv[i], file_list, args.suffix);
          }
          else{ // Non-recursive searching
            pDir = opendir(argv[i]);
            while((myDirent = readdir(pDir)) != NULL)
	          {
		          if(strcmp(myDirent->d_name, ".") == 0 || strcmp(myDirent->d_name, "..") == 0)
		            {
			            continue;
		            } 
              if (myDirent->d_type == 8){
                sprintf(allName, "%s/%s", argv[i], myDirent->d_name);
                string fileName = allName;
                string fsuffix = fileName.substr(fileName.find_last_of('.') + 1); // Get suffix without '.'
                if (args.suffix == "" || strcmp(fsuffix.c_str(), args.suffix.c_str()) == 0)
                  file_list.emplace_back(fileName);   
                }
            }
        }
        }
        else if (s.st_mode & S_IFREG){ // It's a regular file
          string fileName = argv[i];
          string fsuffix = fileName.substr(fileName.find_last_of('.') + 1);
          if (args.suffix == "" || strcmp(fsuffix.c_str(), args.suffix.c_str()) == 0)
            file_list.emplace_back(fileName);}     
        else{
          cout<<"Not a file or a directory!"<<endl;
        }
      }
      else{
        continue;
      }
    }
    // Print fileName and count lines
    if(!args.help){
    cout << "line\tfile" << endl;
    cout<< "----\t----" << endl;
    for (const auto &item: file_list) {
      CountLine(item,args.suffix,args.blank_ignore);
    }
    int cnts;
    cnts = GetAllLine();
    if(args.total_only && file_list.size() > 1) // If only one file, do not output total
        {
          cout << cnts << "\ttotal" <<endl;
        } 
    else{
        PrintFileLine();
        if(file_list.size() > 1)
          cout << cnts << "\ttotal" <<endl;
    }
    }
    return 0;
}
